//
//  User.m
//  DialectShare
//
//  Created by timmy zhong on 3/26/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "User.h"
#import "Const.h"
#import "PathHelper.h"

@interface User ()
+ (NSString *)path;
@end

@implementation User
@synthesize account = _account, password = _password, avatar = _avatar, name = _name, auth = _auth, moto = _moto;
@synthesize uid = _uid, isFollow = _isFollow;
@synthesize dialectCount = _dialectCount, followCount = _followCount, fanCount = _fanCount, commentCount = _commentCount;
- (void)dealloc
{
    self.account = nil;
    self.password = nil;
    self.avatar = nil;
    self.name = nil;
    self.auth = nil;
    self.moto = nil;
    
    [super dealloc];
}

+ (User *)userWithDic:(NSDictionary *)udic
{
    User *user = [[User alloc] init];
    user.uid = [[udic objectForKey:UserUid] intValue];
    user.auth = [udic objectForKey:UserAuth];
    user.account = [udic objectForKey:UserAccount];
    user.name = [udic objectForKey:UserName];
    user.avatar = [udic objectForKey:UserAvatar];
    user.dialectCount = [[udic objectForKey:UserDialectCount] intValue];
    user.followCount = [[udic objectForKey:UserFollowCount] intValue];
    user.fanCount = [[udic objectForKey:UserFanCount] intValue];
    user.commentCount = [[udic objectForKey:UserCommentCount] intValue];
    user.moto = [udic objectForKey:UserMoto];
    user.isFollow = [[udic objectForKey:UserIsFollow] boolValue];
    return [user autorelease];

}

+ (User *)current
{
    NSDictionary *udic = [[NSDictionary alloc] initWithContentsOfFile:[User path]];
    if (udic == nil) {
        return nil;
    }
        
    return [User userWithDic:udic];
}

+ (void)store:(User *)user
{
    NSMutableDictionary *udic = [[NSMutableDictionary alloc] initWithCapacity:20];
    [udic setObject:user.account forKey:UserAccount];
    [udic setObject:user.auth forKey:UserAuth];
    [udic setObject:user.name forKey:UserName];
    [udic setObject:user.avatar forKey:UserAvatar];
    [udic setObject:[NSNumber numberWithInt:user.uid] forKey:UserUid];
    [udic setObject:[NSNumber numberWithInt:user.dialectCount] forKey:UserDialectCount];
    [udic setObject:[NSNumber numberWithInt:user.followCount] forKey:UserFollowCount];
    [udic setObject:[NSNumber numberWithInt:user.fanCount] forKey:UserFanCount];
    [udic setObject:[NSNumber numberWithInt:user.commentCount] forKey:UserCommentCount];
    [udic setObject:user.moto forKey:UserMoto];
    
    [udic writeToFile:[User path] atomically:YES];
    NSLog(@"%@ \n%@", [User path], udic);
    [udic release];
    
    
}

+ (void)logout
{
    [[NSFileManager defaultManager] removeItemAtPath:[User path] error:nil];
}
                       
+ (NSString *)path
{
    return [[PathHelper documentDir] stringByAppendingPathComponent:@"ds_user.plist"];
}

@end
